#!/bin/bash

function cloneRepo() {
  # 仓库地址
  local REPO_URL="$1"

  # 克隆仓库
  git clone $REPO_URL
  REPO_DIR=$(basename $REPO_URL .git)
  cd $REPO_DIR

  # 获取所有远程分支信息
  git fetch --all
}

function fetchAllBranches() {

  # 获取所有远程分支名称
  REMOTE_BRANCHES=$(git branch -r | grep -v HEAD | sed 's/origin\///')

  # 遍历所有远程分支
  for branch in $REMOTE_BRANCHES; do
    # 创建本地分支并切换到该分支
    git checkout -b $branch origin/$branch
    # 拉取该分支的最新代码
    echo "pull branch: ${branch}"
    git pull origin $branch
  done

  # 检查主分支是否为main或master
  if git branch -r | grep -q "origin/main"; then
    git checkout main
  elif git branch -r | grep -q "origin/master"; then
    git checkout master
  else
    echo "警告: 未找到main或master分支"
  fi
}

# 检查是否提供了仓库地址
if [ -z "$1" ]; then
  echo "无仓库地址直接获取全分支代码"
else
  cloneRepo $1
fi
fetchAllBranches

echo "所有分支代码已成功获取。"
